/**  
 * Copyrights@2006, Tianyuan DIC Information Co.,Ltd.
 * 文件名:    TMallOrderCancelHandler.java  
 * 描述:   
 * 作者:     kaiyang
 * 版本:    1.0  
 * 创建时间:   2015年5月4日 下午2:51:28  
 *  
 * 修改历史:  
 * 日期                          作者           版本         描述  
 * ------------------------------------------------------------------  
 * 2015年5月4日      kaiyang      1.0        1.0 Version  
 */ 
package com.hp.bon.sgw.wh.channel.handler;

import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.hp.bon.sgw.Constants;
import com.hp.bon.sgw.Constants.MessageType;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.core.BuzProcessorManager;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.channel.SoapChannel;
import com.hp.bon.sgw.core.channel.handler.IAsynCallHandler;
import com.hp.bon.sgw.domain.MessageDetail;
import com.hp.bon.sgw.threads.MessageDetailCacheManager;
import com.hp.bon.sgw.threads.TaskManager;
import com.hp.bon.sgw.wh.bean.tmall.TMallOrderBean;
import com.hp.bon.sgw.wh.channel.TMallChannel;
import com.hp.bon.sgw.wh.service.TMallResponseService;
import com.hp.bon.sgw.wh.utils.SignUtilsImpl;
import com.hp.ocs.diameter.message.AVP;
import com.hp.ocs.diameter.message.AVP_Grouped;
import com.hp.ocs.diameter.message.AVP_Time;
import com.hp.ocs.diameter.message.AVP_UTF8String;
import com.hp.ocs.diameter.message.Message;

/**  
 * @ClassName: TMallOrderCancelHandler   
 * @Description: TODO  
 * @author: kaiyang  
 * @date:2015年5月4日 下午2:51:28     
 */
public class TMallOrderCancelHandler implements IAsynCallHandler{

	private static final Logger _log = LoggerFactory.getLogger(TaobaoFeeHandle.class);
	private PrintStream printStream;
	private TMallOrderBean tmallOrderBean;
	private TMallResponseService tmallResponseService;
	private ThreadPoolTaskExecutor asynExecutor;
	private String tmallRetUrl;
	private String pubKeyValue;
	
	public TMallOrderCancelHandler(PrintStream printStream,TMallOrderBean tmallOrderBean,TMallResponseService tmallResponseService,ThreadPoolTaskExecutor asynExecutor,String tmallRetUrl,String pubKeyValue)
	{
		this.printStream = printStream;
        this.tmallOrderBean = tmallOrderBean;
        this.tmallResponseService = tmallResponseService;
        this.asynExecutor = asynExecutor;
        this.tmallRetUrl = tmallRetUrl;
        this.pubKeyValue = pubKeyValue;
	}
	
	@Override
	public int getProtocolType() {
		
		return 0;
	}
  
	@Override
	public void onCallResult(CallParam callParam) {
		XmlMessage ack = null;
		Object response = null;
		if (callParam.getResponse() != null) {
			response = callParam.getResponse();
		} else if (callParam.getRecvResponse() != null) {
			response = callParam.getRecvResponse();
		}
		if (response == null) {
			ack = SoapChannel.createERRAnwser(
					callParam.getSessionId(),
					callParam.getRetCode() == 3002 ? 11202 : callParam
							.getRetCode(), callParam.getResultMsg());
		} else {
			if (response instanceof Message) {// CCA -> XML
				ack = BuzProcessorManager.getInstance().convertMessageToAck(
						callParam);
			} else if (response instanceof XmlMessage) {
				ack = (XmlMessage) response;
			} else {
				_log.warn("unknown response type:"
						+ callParam.getResponse().getClass().getName());
			}
		}
		try {
			String respXML = convertResponseString((Message)response,callParam.getServiceResultCode());
			byte[] resp = respXML.getBytes("GBK");
			ack.setLength(resp.length);
			ack.setMsgTime(System.currentTimeMillis());
			printStream.write(resp);
			printStream.close();

			callParam.setResponse(ack);

			if (callParam.getRetCode() == Constants.ResultCode.SUCCESS) {// 成功的消息，请求应答入库

				MessageDetail detail = new MessageDetail();
				detail.setBusinessCallId(callParam.getBussinessCallId());
				detail.setSessionId(callParam.getSessionId());
				detail.setServiceContextId(callParam.getServiceContextId());
				detail.setMessageType(MessageType.WSA);
				detail.setDetails(ack.getDATA());
				detail.setMsgTime(new Date(ack.getMsgTime()));
				detail.setOpType("send");
				detail.setHostId(callParam.getUserName());
				MessageDetailCacheManager.getInstance().add(detail);
			}
			TaskManager.taskProcess(callParam);
			_log.info("http response(taobao) " + respXML);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	private String convertResponseString(Message answer, int serviceResultCode)
	{
		String response = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		Map<String,String> data = new HashMap<String, String>();
		data.put("tbOrderNo",tmallOrderBean.getTbOrderNo());
		if (serviceResultCode == 0) {
			String reverseSerialNbr = "";
			String reverseDate = "";
			try{
			    //service_infomation
			    AVP avp = answer.find(Constants.DIAMETER_AVP_SERVICE_INFOMATION,Constants.DIAMETER_VENDOR_3GPP);
			    AVP_Grouped avpServiceInfomation = new AVP_Grouped(avp);
			    //reverse_serial_nbr
			    AVP avpReverseSerialNbr = avpServiceInfomation.find(80155,Constants.DIAMETER_VENDOR_CT);
			    if (avpReverseSerialNbr != null)
			        reverseSerialNbr = new AVP_UTF8String(avpReverseSerialNbr).queryValue();
			    //reverse_date
			    AVP avpReverseDate = avpServiceInfomation.find(80157, Constants.DIAMETER_VENDOR_CT);
			    if (avpReverseDate != null)
			    {
			    	Date date = new AVP_Time(avpReverseDate).queryDate();
			    	reverseDate = sdf.format(date);
			    }
				data.put("coopOrderNo",reverseSerialNbr);
				data.put("coopOrderStatus",TMallChannel.STATUS_SUCCESS);
				data.put("coopOrderSnap","ReCharge");
				data.put("coopOrderSuccessTime",reverseDate);
				data.put("failedCode","");
				data.put("failedReason","");
				Map<String,String> paraMap = new TreeMap<String, String>();
				String coopId = tmallOrderBean.getCoopId();
				String tbOrderNo = tmallOrderBean.getTbOrderNo();
				String coopOrderNo = data.get("coopOrderNo");
				String coopOrderStatus = TMallChannel.CANCEL;
				String failedCode = "0901";
				paraMap.put("coopId", coopId);
				paraMap.put("tbOrderNo", tbOrderNo);
				paraMap.put("coopOrderNo", coopOrderNo);
				paraMap.put("coopOrderStatus", coopOrderStatus);
				paraMap.put("failedCode",failedCode);
				paraMap.put("failedReason", failedCode);
				String source = "";
				for(Entry<String,String> entry:paraMap.entrySet())
				{
					source += entry.getKey()+entry.getValue();
				}
				source = source + pubKeyValue;
				String sign = SignUtilsImpl.getTmallSign(source);
				paraMap.put("sign",sign);
				TMallRetTask task = new TMallRetTask(tmallRetUrl, paraMap);
				asynExecutor.execute(task);		
				
			}catch(Exception e){
				data.put("coopOrderNo",tmallOrderBean.getTbOrderNo());
				data.put("coopOrderStatus",TMallChannel.REQUEST_FAIL);
				data.put("coopOrderSnap","ReCharge");
				data.put("coopOrderSuccessTime","");
				data.put("failedCode", "0104");
				data.put("failedReason","");
				e.printStackTrace();
			}			
		}
		else
		{
			data.put("coopOrderNo",tmallOrderBean.getTbOrderNo());
			data.put("coopOrderStatus",TMallChannel.REQUEST_FAIL);
			data.put("coopOrderSnap","ReCharge");
			data.put("coopOrderSuccessTime","");
			data.put("failedCode", "0104");
			data.put("failedReason","");
		}
		response = tmallResponseService.getResponse(data);
		return response;
	}
}
